from django.db import transaction

from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException
from .errors import *
from .models import Account


def list_admin_user(page_no, page_size):
    query = Account.objects.all(deleted=False)
    return query.count(), [e.to_dict() for e in paginate(query, page_no, page_size)]


def _get_admin_account(admin_account_id):
    admin = Account.objects.filter(pk=admin_account_id).first()
    if not admin:
        raise BizException(ERROR_ADMIN_ACCOUNT_NOT_EXISTS)
    return admin


def get_admin_account_by_id(admin_account_id):
    assert admin_account_id
    admin = Account.objects.filter(pk=admin_account_id, user__deteled=False).first()
    return admin.to_dict()


def update_admin_account(admin_account_id, use_vcode=None):
    assert admin_account_id
    with transaction.atomic():
        account = _get_admin_account(admin_account_id)
        if use_vcode is not None:
            account.use_vcode = use_vcode
        account.save()
